package com.coldchain.authclient.interceptor;

import com.coldchain.authclient.annotation.IgnoreUserToken;
import com.coldchain.authclient.config.UserAuthConfig;
import com.coldchain.authclient.jwt.UserAuthUtil;
import com.coldchain.authclient.annotation.CheckUserToken;
import com.coldchain.common.constant.RequestHeaderConstants;
import com.coldchain.common.exception.auth.NonLoginException;
import com.fangliai.core.constants.CommonConstants;
import com.fangliai.core.context.BaseContextHandler;
import com.fangliai.core.util.jwt.IJWTInfo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户认证拦截器,检测用户tokne的有效性
 * @CheckUserToken 用户枝限检查
 * @IgnoreUserToken 忽略用户鉴权
 * @ClassName UserAuthRestInterceptor
 * @Author fangliai
 * @Date 2018/8/30 9:56
 * @Vesion 1
 **/
@Configuration
@ComponentScan("com.fangliai")
public class UserAuthRestInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(UserAuthRestInterceptor.class);

    @Autowired
    private UserAuthUtil userAuthUtil;

    @Autowired
    private UserAuthConfig userAuthConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        CheckUserToken annotation = handlerMethod.getBeanType().getAnnotation(CheckUserToken.class);
        IgnoreUserToken ignoreUserToken = handlerMethod.getMethodAnnotation(IgnoreUserToken.class);
        if (annotation == null) {
            annotation = handlerMethod.getMethodAnnotation(CheckUserToken.class);
        }
        if (annotation == null || ignoreUserToken != null) {
            return super.preHandle(request, response, handler);
        } else {
            String token = request.getHeader(userAuthConfig.getTokenHeader());
            if (StringUtils.isEmpty(token)) {
                if (request.getCookies() != null) {
                    for (Cookie cookie : request.getCookies()) {
                        if (cookie.getName().equals(userAuthConfig.getTokenHeader())) {
                            token = cookie.getValue();
                        }
                    }
                }
            }
             String oldToken=token;
             if (token != null && token.startsWith(RequestHeaderConstants.JWT_TOKEN_TYPE)) {
                token = token.substring(RequestHeaderConstants.JWT_TOKEN_TYPE.length(),token.length());
            }else {
                 throw  new NonLoginException("用户身份验证失败");
             }
            try {
                IJWTInfo infoFromToken = userAuthUtil.getInfoFromToken(token);
                BaseContextHandler.setToken(oldToken);
                BaseContextHandler.setUsername(infoFromToken.getUniqueName());
                BaseContextHandler.setName(infoFromToken.getName());
                BaseContextHandler.setUserID(infoFromToken.getId());
                BaseContextHandler.setSysModl(infoFromToken.getOtherInfo().get(CommonConstants.JWT_KEY_SYS_MODEL));
                BaseContextHandler.setCysID(infoFromToken.getOtherInfo().get(CommonConstants.JWT_KEY_CYS_ID));
                BaseContextHandler.setCommpanyIdID(infoFromToken.getOtherInfo().get(CommonConstants.JWT_KEY_COMMPANY_ID));
            }catch(NonLoginException ex){
//                 response.setStatus(HttpStatus.UNAUTHORIZED.value());
//                response.setContentType("UTF-8");
//                response.getOutputStream().println(JSON.toJSONString(new BaseResponse(ex.getStatus(), ex.getMessage())));
//                logger.error(ex.getMessage(),ex);
                // return false;
                throw  new NonLoginException("用户身份验证失败");
            }

            return super.preHandle(request, response, handler);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContextHandler.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}
